import { Config } from "config.js";
import { Base64 } from "base64.js";
var u = require("../utils/util.js"), h = require("../utils/http.js"), a = require("../utils/api.js"), 
utilMd5 = require('../utils/md5.js'), base64 = new Base64();

class Token {

  constructor() {
    this.getTokenUrl = 'https://otoapi.zmmedical.cn/api/token';     
    this.data = {
      appid: Config.appid,
      nonce: this._getNum(),
      timestamp: new Date().getTime(),
    };
  }

  // 从服务器获取token
  getTokenFromServer() {
    var t= this;
    var datas = {
      appid: t.data.appid,
      nonce: t.data.nonce,
      timestamp: t.data.timestamp,
      sign: t._generateSign(t.data, Config.app_secret)
    };
    var header = {
      'content-type': 'application/json'      
    } 
    wx.request({
      url: t.getTokenUrl,
      header: header,
      data: datas,
      method: 'post',
      success: function (res) {
        var data = res.data.data;
        // console.log(data);
        if (res.data.code == 200) {
          var token = data.access_token;
          var base64Str = base64.encode(Config.appid + ':' + token);
          h.header.authentication = base64Str;
          a.storeId = data.store_id;
          wx.setStorageSync('keys', base64Str);
          wx.setStorageSync('keys_time', t.data.timestamp);
          wx.setStorageSync('keys_expire', data.expire);
          wx.setStorageSync('store_id', data.store_id);
        }else{
          wx.showModal({
            title: '请求错误',
            content: '获取token失败',
            showCancel: false,
            success:function(){}
          })
        }
      },
      fail: function () {
        wx.showModal({
          title: '请求错误',
          content: '网络出错，请刷新重试',
          showCancel: false
        })
      }
    })
  }

  // 生成签名
  _generateSign(data, secret) {
    data['key'] = secret;
    data = this._objKeySort(data);
    // console.log(data);
    data = this._http_build_query(data);
    data = utilMd5.hexMD5(data);
    data = data.toLowerCase();
    return data;
  } 
  
  //排序的函数
  _objKeySort(obj) {
    var newkey = Object.keys(obj);
    //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，     newkey是一个数组
    var newObj = {};//创建一个新的对象，用于存放排好序的键值对
    for (var i = 0; i < newkey.length; i++) {//遍历newkey数组
      newObj[i] = obj[newkey[i]].toString();//向新创建的对象中按照排好的顺序依次增加键值对  
    }
    newObj = Object.values(newObj).sort();
    return newObj;//返回排好序的新对象
  }

  _http_build_query(obj) {
    var newkey = Object.keys(obj);
    var newvalue = Object.values(obj);
    var str = '';
    for (var i = 0; i < newkey.length; i++) {
      if (i == newkey.length - 1) {
        str += newkey[i] + '=' + newvalue[i];
      } else {
        str += newkey[i] + '=' + newvalue[i] + '&';
      }
    }
    return str;
  }

  // 生成32位随机数
  _getNum() {
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    var nums = "";
    for (var i = 0; i < 32; i++) {
      var id = parseInt(Math.random() * 61);
      nums += chars[id];
    }
    return nums;
  }
}
export { Token };
